package com.cloudcc.mobile.util;

import com.cloudcc.mobile.R;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.Bitmap.Config;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class Watermark extends Activity {
	ImageView imageView;
	Bitmap mark;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_watermark);
		imageView = (ImageView) findViewById(R.id.water_image);
		// 设置图片来源
		imageView.setImageResource(R.drawable.arrow_down);
		mark = BitmapFactory.decodeResource(getResources(),
				R.drawable.ic_launcher);

		Button button = (Button) findViewById(R.id.button_water);

		button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Bitmap temp = watermark(
						drawableToBitmap(imageView.getDrawable()), mark, 50,
						100);
				imageView.setImageBitmap(temp);
			}
		});
	}

	/**
	 * 将bitmap转换为Drawable
	 * 
	 * @param bitmap
	 * @return
	 */
	public static Drawable bitmapToDrawable(Bitmap bitmap) {
		BitmapDrawable bd = new BitmapDrawable(bitmap);
		return bd;
	}

	/**
	 * @param src
	 * @param bg
	 * @param color
	 * @return
	 */
	public static Bitmap watermark(Bitmap src, Bitmap mark, int x, int y) {
		int w = src.getWidth();
		int h = src.getHeight();
		Bitmap newb = Bitmap.createBitmap(w, h, Config.ARGB_8888);
		Canvas cv = new Canvas(newb);
		cv.drawBitmap(src, 0, 0, null);
		cv.drawBitmap(mark, x, y, null);
//		cv.save(Canvas.ALL_SAVE_FLAG);// 保存
		cv.save();
		cv.restore();// 存储
		return newb;
	}

	/**
	 * Drawable 转换为Bitmap
	 * 
	 * @param drawable
	 * @return
	 */
	public static Bitmap drawableToBitmap(Drawable drawable) {
		// 取 drawable 的长宽
		int w = drawable.getIntrinsicWidth();
		int h = drawable.getIntrinsicHeight();
		// 取 drawable 的颜色格式
		Config config = drawable.getOpacity() != PixelFormat.OPAQUE ? Config.ARGB_8888
				: Config.RGB_565;
		Bitmap bitmap = Bitmap.createBitmap(w, h, config);
		Canvas canvas = new Canvas(bitmap);
		drawable.setBounds(0, 0, w, h);
		drawable.draw(canvas);
		return bitmap;
	}

}
